/**************************************************************************//**
 * @item     CosyOS Kernel
 * @file     debug.c
 * @brief    DEBUG接口
 * @author   迟凯峰
 * @version  V2.3.3
 * @date     2023.05.08
 ******************************************************************************/

#include "syslink.h"

#if MCUCFG_MCULEVEL == __FEIPAOZI__

static char* _strncpy_(char* src, const char* sub, size_t n)
{
	if(src == NULL || sub == NULL || !*sub || !n)
	{
		return src;
	}
	else
	{
		char* str = src;
		do{
			*str++ = *sub;
			if(!*sub++)
			{
				return src;
			}
		}while(--n);
		*str = '\0';
		return src;
	}
}

static char _strncmp_(const char* src, const char* sub, size_t n)
{
	if(src == NULL || sub == NULL)
	{
		return 1;
	}
	do{
		if(*src++ == *sub)
		{
			if(!*sub++)
			{
				return 0;
			}
		}
		else
		{
			return 1;
		}
	}while(--n);
	return 0;
}

static int _atoi_(const char* str)
{
	if(str == NULL || !*str)
	{
		return 0;
	}
	else
	{
		int A = 0;
		int K = 1;
		u8  i = __strlen(str);
		while(i--)
		{
			if(str[i] >= '0' && str[i] <= '9')
			{
				A += (str[i] - '0') * K;
				K *= 10;
			}
			else if(str[i] == '+')
			{
				return A;
			}
			else if(str[i] == '-')
			{
				return -A;
			}
			else
			{
				return 0;
			}
		}
		return A;
	}
}

#else
#define _strncpy_ strncpy
#define _strncmp_ strncmp
#define _atoi_    atoi
#endif

static void _debug_recv_(void)
{
	#define	hptr vDebugRecvBuff
	u16  temp;
	char _DEBUG_LREG_ strtmp[8];
	char _DEBUG_LMEM_ * _DEBUG_LREG_ mptr = hptr;
	char _DEBUG_LMEM_ * _DEBUG_LREG_ tptr = hptr + __strlen(hptr) - 2;
	if(!__strcmp(tptr, "\r\n"))
	{
		if(!__strcmp(hptr, "taskmgr\r\n"))
		{
			uFreeBin(vTaskmgrBinary);
		}
		else if(!__strcmp(hptr, "exit\r\n"))
		{
			uLockBin(vTaskmgrBinary);
		}
		else if(!_strncmp_(hptr, "taskmgr /s=", 11))
		{
			mptr += 11;
			_strncpy_(strtmp, mptr, tptr - mptr);
			strtmp[tptr - mptr] = '\0';
			temp = _atoi_(strtmp);
			if(temp >= 50 && temp <= 5000)
			{
				mEnterCritical;
				vTIMQRY_BUFF[__TMID_TASKMGR__] = (1000UL * temp) / SYSCFG_STKCYCLE;
				mExitCritical;
			}
		}
	}
}

uCreateHook_TimQry(SYSCFG_USERTIMQRYTOTAL, vDebugSendFlag, false, debug_hook)
{
	if(vDebugSendFlag & CmdlineSendFlag)
	{
		vDebugSendFlag &= ~CmdlineSendFlag;
		vDebugSendPtr = vCmdLineSendBuff;
		SYSCFG_DEBUGSEND;
	}
	else if(vDebugSendFlag & TaskmgrSendFlag)
	{
		vDebugSendFlag &= ~TaskmgrSendFlag;
		vDebugSendPtr = vTaskmgrSendBuff;
		SYSCFG_DEBUGSEND;
	}
}

uCreateTask_TimInt(SYSCFG_USERTIMINTTOTAL, false, Debugger, SYSCFG_TASKPRIORITY - 1, __STACKSIZE_DEBUGGER__, 0, 0)
{
	vDebugRecvPtr[0] = '\0';
	_debug_recv_();
	vDebugRecvPtr = vDebugRecvBuff;
	uSuspendTasking;
	uEndTasking;
}
